package com.cmcc.aregister.ui.activity;

import java.util.HashMap;
import java.util.Map;

import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.cmcc.aregister.R;
import com.cmcc.aregister.cs.constant.Arguments;
import com.cmcc.aregister.cs.constant.ConfigUtilHelper;
import com.cmcc.aregister.cs.constant.GlobalSetting;
import com.cmcc.aregister.cs.database.DatabaseAdapter;
import com.cmcc.aregister.cs.http.HttpAsyncTask;
import com.cmcc.aregister.cs.model.User;
import com.cmcc.aregister.cs.util.PotoalParcelable;
import com.cmcc.aregister.cs.util.Utils;

public class MemberCenterActivity extends ParentActivity
{
    private final String TAG = "MemberCenterActivity";
    private LinearLayout personal_layout, family_layout, haoyuan_layout,
        zidong_layout, jiuzhen_layout, mymessage_layout, yuyue_layout,
        collet_layout;
    private boolean isLogin = false;
    private DatabaseAdapter mDatabaseAdapter;
    private boolean canCheckOtherMsg = false;
    boolean isSet = false;
    private String card_type;
    private String params;
    private boolean isHaoyuanTip = false;

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        init(R.layout.p_member_center);
        mHttpManager.setCxt(getParent());
    }

    /**
     * 判断提示注册
     */
    private void showRegister()
    {
        if (ConfigUtilHelper.isLogin(app)
            && ConfigUtilHelper.getUsername(app).equals(""))
        {
            showDoubleDlg_(getString(R.string.notice),
                getString(R.string.dialog_no_register1),
                getString(R.string.dialog_sure_register1),
                getString(R.string.dialog_back_index));
        }
    }

    @Override
    protected void onResume()
    {
        super.onResume();
        canCheckOtherMsg = false;
        isLogin = ConfigUtilHelper.isLogin(this);
        showRegister();
        SharedPreferences infoVisiblePre = getSharedPreferences(
            ConfigUtilHelper.INFO_VISIBLE_PREFS, Context.MODE_PRIVATE);
        isSet = infoVisiblePre.getBoolean(ConfigUtilHelper.info_visible_set,
            false);
        if (isSet)
        {
            if (isLogin)
            {
                canCheckOtherMsg = true;
            }
        }
        else
        {
            mDatabaseAdapter.open_user();
            Cursor c = mDatabaseAdapter.fetchAllUserData();
            if (c != null && c.getCount() > 0)
            {
                canCheckOtherMsg = true;
            }
            c.close();
            mDatabaseAdapter.close_user();
        }
    }

    @Override
    protected void setupView()
    {
        ImageView iv_title = (ImageView) findViewById(R.id.title);
        iv_title.setBackgroundResource(R.drawable.center_title);
        // ((TextView) findViewById(R.id.title)).setText(R.string.myservice);
        personal_layout = (LinearLayout) findViewById(R.id.personal_layout);
        family_layout = (LinearLayout) findViewById(R.id.family_layout);
        haoyuan_layout = (LinearLayout) findViewById(R.id.haoyuan_layout);
        zidong_layout = (LinearLayout) findViewById(R.id.zidong_layout);
        // jiuzhen_layout = (LinearLayout) findViewById(R.id.jiuzhen_layout);
        mymessage_layout = (LinearLayout) findViewById(R.id.mymessage_layout);
        yuyue_layout = (LinearLayout) findViewById(R.id.yuyue_layout);
        collet_layout = (LinearLayout) findViewById(R.id.collet_layout);

        personal_layout.setOnClickListener(onClickListener);
        family_layout.setOnClickListener(onClickListener);
        personal_layout.setOnClickListener(onClickListener);
        haoyuan_layout.setOnClickListener(onClickListener);
        zidong_layout.setOnClickListener(onClickListener);
        // jiuzhen_layout.setOnClickListener(onClickListener);
        mymessage_layout.setOnClickListener(onClickListener);
        yuyue_layout.setOnClickListener(onClickListener);
        collet_layout.setOnClickListener(onClickListener);
    }

    @Override
    protected void setupData()
    {
        mDatabaseAdapter = new DatabaseAdapter(this);
    }

    OnClickListener onClickListener = new OnClickListener() {
        @Override
        public void onClick(View v)
        {
            int id = v.getId();
            switch (id)
            {
            case R.id.personal_layout:
                if (canCheckOtherMsg)
                {
                    gotoPersonal();
                }
                else
                {
                    gotoLogin();
                }
                break;
            case R.id.family_layout:
                if (canCheckOtherMsg)
                {
                    gotoFamily();
                }
                else
                {
                    gotoLogin();
                }
                break;
            case R.id.haoyuan_layout:
                if (canCheckOtherMsg)
                {
                    isHaoyuanTip = true;
                    vaildVipTask();
                }
                else
                {
                    gotoLogin();
                }
                break;
            case R.id.zidong_layout:
                if (canCheckOtherMsg)
                {
                    isHaoyuanTip = false;
                    vaildVipTask();
                }
                else
                {
                    gotoLogin();
                }
                break;

            case R.id.yuyue_layout:
                if (canCheckOtherMsg)
                {
                    gotoAppManager();
                }
                else
                {
                    gotoLogin();
                }
                break;
            case R.id.collet_layout:
                if (canCheckOtherMsg)
                {
                    gotoCollet();
                }
                else
                {
                    gotoLogin();
                }
                break;
            }
        }
    };

    private HttpAsyncTask sendGetUserInfoTask;

    /**
     * 个人信息
     */
    private void gotoPersonal()
    {
        Map<String, String> parameterMap = new HashMap<String, String>();
        parameterMap.put("mobile", ConfigUtilHelper.getMobile(app));
        String changeUserInfoUrl = Utils.changeUrl(
            Arguments.SERVER_URL_GET_USER_INFO, parameterMap);
        sendGetUserInfoTask = new HttpAsyncTask(HttpAsyncTask.GET,
            GlobalSetting.XML_GET_USER_INFO, changeUserInfoUrl,
            HttpAsyncTask.CACHE_TYPE_ACTION, false);
        showProgressDialog();
        sendGetUserInfoTask.setUIHandler(sendGetUserInfoTaskHandler);
        mHttpManager.execute(sendGetUserInfoTask);

    }

    @SuppressWarnings("unchecked")
    Handler sendGetUserInfoTaskHandler = new Handler() {
        public void handleMessage(Message msg)
        {
            logger.d("----------sendGetUserInfoTaskHandler----------");
            switch (msg.what)
            {
            case HttpAsyncTask.TASK_NOTIFY_RETURN_DATA:
                if (msg.obj != null)
                {
                    Map<String, Object> httpMap = (Map<String, Object>) msg.obj;
                    User user_new = (User) httpMap.get(Arguments.XML_USER);
                    if ("".equals(user_new.card)
                        || "null".equals(user_new.card))
                    {
                        dismissProgressDialog();
                        showMsg(R.string.no_register);
                        gotoEditUserInfo(false);
                    }
                    else
                    {
                        Intent intent_1 = new Intent(MemberCenterActivity.this,
                            PersonalInfoActivity.class);
                        Map<String, Object> userInfoMap = new HashMap<String, Object>();
                        userInfoMap.put("name", user_new.name);
                        userInfoMap.put("sex", user_new.sex);
                        userInfoMap.put("birth", user_new.birth);
                        userInfoMap.put("card", user_new.card);
                        userInfoMap.put("socialCard", user_new.social_card);
                        PotoalParcelable potoal = new PotoalParcelable(
                            userInfoMap);
                        intent_1
                            .putExtra(Arguments.INTENT_TO_NEXT_PAGE, potoal);
                        intent_1.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                        startActivity(intent_1);
                    }
                }
                else
                {
                    dismissProgressDialog();
                    showMsg(R.string.no_register);
                    gotoEditUserInfo(false);
                }
                break;
            case HttpAsyncTask.TASK_NOTIFY_CONNECTION_FAIL:
                dismissProgressDialog();
                showSingleAlertDlg(getString(R.string.notice),
                    getString(R.string.load_user_info_err_and_no_edit),
                    getString(R.string.close));
                break;
            }
        }
    };

    // 回到个人信息编辑界面
    private void gotoEditUserInfo(boolean isRegister)
    {
        Intent intent = new Intent(MemberCenterActivity.this,
            PersonInfoEditor.class);
        intent.putExtra(Arguments.ACTIVITY_IS_USER, isRegister);
        intent.putExtra(Arguments.ACTIVITY_CARD_TYPE, card_type);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        startActivity(intent);
    }

    /**
     * 家庭成员信息
     */
    private void gotoFamily()
    {
        Intent intent = new Intent(MemberCenterActivity.this,
            NewMyServiceActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        startActivity(intent);
        finish();
    }

    /**
     * 我的预定
     */
    private void gotoAppManager()
    {
        Intent intent = new Intent(MemberCenterActivity.this,
            AppManagerActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        startActivity(intent);

    }

    /**
     * 我的收藏
     */
    private void gotoCollet()
    {
        Intent intent = new Intent(MemberCenterActivity.this,
            CustomManagerActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        startActivity(intent);
    }

    /**
     * 跳转到登陆界面
     */
    private void gotoLogin()
    {
        Intent intent = new Intent(MemberCenterActivity.this,
            UserLoginActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        startActivity(intent);
    }

    /**
     * 验证VIP用户
     */
    private HttpAsyncTask vaildVipTask;

    /**
     * 验证VIP
     */
    private void vaildVipTask()
    {
        JSONObject obj = new JSONObject();
        try
        {
            obj.put("request_type", Arguments.ValidVIPUserRemoting);
            obj.put("user_mobile", ConfigUtilHelper.getMobile(app));
            obj.put("channel", "medical_client_android");
            obj.put("version",
                ConfigUtilHelper.getVersionName(getApplication()));
            if (isHaoyuanTip)
            {
                obj.put("oper_type", Arguments.OPER_TYPE_SOURCE_REMIND);
            }
            else
            {
                obj.put("oper_type", Arguments.OPER_TYPE_AUTO_APPOINT);
            }
        }
        catch (JSONException e)
        {
            e.printStackTrace();
        }
        params = obj.toString();
        String url = Arguments.GET_AUTO_APPOINT_SERVICE_URL;
        vaildVipTask = new HttpAsyncTask(GlobalSetting.XML_VALID_VIP, url,
            params, HttpAsyncTask.CACHE_TYPE_ACTION, true, true);
        showProgressDialogNew(R.string.valid_vip_loading);
        vaildVipTask.setUIHandler(vaildVipTaskHandler);
        mHttpManager.execute(vaildVipTask);
    }

    @SuppressWarnings("unchecked")
    Handler vaildVipTaskHandler = new Handler() {
        public void handleMessage(Message msg)
        {
            switch (msg.what)
            {
            case HttpAsyncTask.TASK_NOTIFY_RETURN_DATA:
                dismissProgressDialog();
                if (msg.obj != null)
                {
                    Map<String, Object> map = (Map<String, Object>) msg.obj;
                    String isVip = (String) map.get(Arguments.JSON_ISVIP);
                    String message = (String) map.get(Arguments.RESULT_MSG);
                    if (isVip.equals("0"))
                    {
                        Intent intent = null;
                        if (isHaoyuanTip)
                        {
                            intent = new Intent(MemberCenterActivity.this,
                                HaoyuanTipActivity.class);
                        }
                        else
                        {
                            intent = new Intent(MemberCenterActivity.this,
                                AppointActivity.class);
                        }
                        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                        startActivity(intent);
                    }
                    else
                    {
                        showSingleAlertDlg(getString(R.string.notice), message,
                            getString(R.string.close));
                    }
                }
                else
                {
                    showMsg(R.string.read_member_fail);
                }
                break;
            case HttpAsyncTask.TASK_NOTIFY_CONNECTION_FAIL:
                dismissProgressDialog();
                showSingleAlertDlg(getString(R.string.notice),
                    getString(R.string.valid_vip_failure),
                    getString(R.string.close));
                break;
            }
        };
    };

    @Override
    protected void onDestroy()
    {
        // TODO Auto-generated method stub
        super.onDestroy();
        if (ConfigUtilHelper.debug)
        {
            Log.i(TAG, "------onDestroy------");
        }
    }

    @Override
    protected void onPause()
    {
        // TODO Auto-generated method stub
        super.onPause();
        if (ConfigUtilHelper.debug)
        {
            Log.i(TAG, "------onPause------");
        }
    }

    @Override
    protected void onRestart()
    {
        // TODO Auto-generated method stub
        super.onRestart();
        if (ConfigUtilHelper.debug)
        {
            Log.i(TAG, "------onRestart------");
        }
    }
}
